<?php

class multitender_action_list_sites extends multitender_action {

    function run() {
        $ls = $this->new_model('list_sites');

        $link = $this->conf['pref']['link_base'];

        $tpl = $this->new_tpl();
        $tpl->caching = true;
        $tpl->cache_lifetime = $this->conf['cache_lifetime'];

        $show = 0;
        if ($this->conf['user']['payment_type'] === 'unlimited') {
            $show = 1;
        }

        @ $page = (int) $_GET['page'];
        if ($page < 1) {
            $page = 1;
        }

        if (!$tpl->is_cached('list_sites.tpl', "list_sites|page$page|$show")) {
            echo("<!-- list_sites: db -->");

            $items = $ls->get_item_count_sites();

            foreach ($items as $item) {
                if ($item['total'] > 0) {
                    $site_ids[] = $item['site_id'];
                }
            }

            $this->total    = $ls->get_sites_count($site_ids);
            $this->rectopg  = 50;

            $scrol=$this->new_action("scrol");
            $scrol->link= $link."action=list_sites".$scrol->link;
            $scrol->total=$this->total;
            $scrol->onpage = $this->rectopg;
            $tpl->assign('scrol', $scrol->run());

            $sites = $ls->get_sites($site_ids, ($scrol->page-1)*$this->rectopg, $this->rectopg);

            foreach ($sites as $site) {
                if (!empty($site['region_id'])) {
                    $region_ids[] = $site['region_id'];
                }
            }

            $regions = $ls->get_regions();

            foreach ($sites as &$site) {
                if ($show) {
                    $site['link'] = 'http://'.$site['url'];
                }
                foreach ($items as $item) {
                    if ($item['site_id']==$site['id']) {
                        $site['item_total'] = $item['total'];
                    }
                }
                foreach ($regions as $region) {
                    if ($site['region_id']==$region['id']) {
                        $site['region_name'] = $region['sname'];
                    }
                }
            }
            $tpl->assign('total', $this->total);
            $tpl->assign('sites', $sites);
            $tpl->assign('link',  $this->conf['pref']['link_base']);
        } else {
            echo("<!-- list_sites: cache -->");
        }

        return $tpl->fetch('list_sites.tpl', "list_sites|page$page|$show");
    }

}

